<?php
require_once '../libs/Smarty.class.php';
require_once '../util/auth.php';
$smarty = new Smarty ();

//$smarty->force_compile = true;
//$smarty->debugging = true;
$smarty->caching = false;
//$smarty->cache_lifetime = 120;

if ($_SERVER ["REQUEST_METHOD"] == "POST") {
	// POST method : user post a register form
	
	if (isset ( $_POST ["username"] ) && isset ( $_POST ["password"] ) && isset ( $_POST ["repassword"] ) && isset ( $_POST ["email"] )) {
		require_once $_SERVER ["DOCUMENT_ROOT"] . '/util/dbconnect.php';
		$username = $_POST ["username"];
		$password = $_POST ["password"];
		$repassword = $_POST ["password"];
		$email = $_POST ["email"];
		$ip = $_SERVER['REMOTE_ADDR'];
		if ($password != $repassword) {
			die ( "两次密码输入不相符" );
		}
		$db->exec ( sprintf ( 'INSERT INTO `user` (`username`, `password`, `email`, `last_ip`) values("%s", "%s", "%s", "%s");', $username, $password, $email, $ip ) );
		if ($db->errorCode()==0){
			// errorCode gonna be '00000'
			$uid = $db->lastInsertId();
			setLoggedIn($uid, $username);
			$smarty->assign("msgTitle", "注册成功");
			$smarty->assign("message", "注册成功!");
			$smarty->assign("location", "login.php");
			$smarty->display("../info_redirect.tpl");
		}
		else{
			$smarty->assign("msgTitle", "注册失败");
			$info = $db->errorInfo();
			$infoStr = $info[2];
			$smarty->assign("message", "注册失败,用户名已存在.".$infoStr.'errno: #'.$db->errorCode());
			$smarty->display("../info_back.tpl");
		}
	} else {
		die ( "Need full info." );
	}
} else {
	//GET method
	@session_destroy ();
	$smarty->display ( '../cpanel/register.tpl' );
}
